import React, { useCallback } from 'react'
import { LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons'
import { Avatar, Menu, Spin } from 'antd'
import { history, useModel } from 'umi'
import { getPageQuery, StoreKey, delStore } from '@/utils/util'
import { HttpLoginOut } from '@/services/login'
import { stringify } from 'querystring'
import HeaderDropdown from '../HeaderDropdown'
import styles from './index.less'

export interface GlobalHeaderRightProps {
    menu?: boolean
}

/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async () => {
    await HttpLoginOut()
    await delStore(StoreKey.TOKEN)
    const { redirect } = getPageQuery()
    if (history.location.pathname !== '/login' && !redirect) {
        history.replace({
            pathname: '/login',
            search: stringify({
                redirect: history.location.pathname,
            }),
        })
    }
}

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu }) => {
    const { initialState, setInitialState } = useModel('@@initialState')

    const onMenuClick = useCallback(
        (event: {
            key: React.Key
            keyPath: React.Key[]
            item: React.ReactInstance
            domEvent: React.MouseEvent<HTMLElement>
        }) => {
            const { key } = event
            if (key === 'logout') {
                setInitialState({ ...initialState, user: undefined })
                loginOut().then()
                return
            }
            history.push(`/${key}`)
        },
        [],
    )

    const loading = (
        <span className={`${styles.action} ${styles.account}`}>
            <Spin
                size='small'
                style={{
                    marginLeft: 8,
                    marginRight: 8,
                }}
            />
        </span>
    )

    if (!initialState) {
        return loading
    }

    const { user } = initialState

    if (!user || !user.userid) {
        return loading
    }

    const menuHeaderDropdown = (
        <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
            {menu && (
                <Menu.Item key='center'>
                    <UserOutlined />
                    个人中心
                </Menu.Item>
            )}
            {menu && (
                <Menu.Item key='settings'>
                    <SettingOutlined />
                    个人设置
                </Menu.Item>
            )}
            {menu && <Menu.Divider />}

            <Menu.Item key='logout'>
                <LogoutOutlined />
                退出登录
            </Menu.Item>
        </Menu>
    )
    return (
        <HeaderDropdown overlay={menuHeaderDropdown}>
            <span className={`${styles.action} ${styles.account}`}>
                <Avatar
                    size='small'
                    className={styles.avatar}
                    src={user.avatar || '/logo.png'}
                    alt='avatar'
                />
                <span className={`${styles.name} anticon`}>{user.name}</span>
            </span>
        </HeaderDropdown>
    )
}

export default AvatarDropdown
